<template>
  <div class="box">
    <el-row>
      <el-form :inline="true" :model="filterField" ref="searchConditions">
        <el-col :span="24">
          <el-form-item label="选择区域">
            <el-cascader
              ref="manageArea"
              v-model="areaId"
              :append-to-body="false"
              :options="areasOptions"
              filterable
              :props="{ checkStrictly: true, emitPath: false }"
              @change="changeArea"
            ></el-cascader>
          </el-form-item>
          <el-button
            class="commonBut saveBtn fr"
            @click="toSave"
            :loading="isAdd"
            >保存</el-button
          >
        </el-col>
        <el-col :span="24" class="border">
          <div class="secondaryTitle secondaryTitleTheme">保险开关设置</div>
          <div class="switch">
            <span>功能开关</span
            ><el-switch
              v-model="choice"
              active-value="1"
              inactive-value="0"
              @change="changeChoice"
            >
            </el-switch>
          </div>
        </el-col>
        <el-col :span="24" class="border">
          <div class="secondaryTitle secondaryTitleTheme">审核配置</div>
          <div class="audit">
            <ul>
              <li class="clearfix">
                <el-checkbox
                  v-model="checked[0]"
                  true-label="1"
                  false-label="0"
                  class="fl"
                ></el-checkbox>
                <span class="level fl">监察审核（一级）账号：</span>
                <div class="fl accountBox">
                  <span v-for="(item, index) of usersList[0]" :key="index"
                    >{{ item.nickname }}（{{ item.username }}）<span
                      v-show="index != usersList[0].length - 1"
                      >、</span
                    ></span
                  >
                  <el-link icon="el-icon-edit" class="icon" @click="toEdit(0)"
                    >编辑</el-link
                  >
                </div>
              </li>
              <li class="clearfix">
                <el-checkbox
                  v-model="checked[1]"
                  true-label="1"
                  false-label="0"
                  class="fl"
                ></el-checkbox>
                <span class="level fl">监察审核（二级）账号：</span>
                <div class="fl accountBox">
                  <span v-for="(item, index) of usersList[1]" :key="index"
                    >{{ item.nickname }}（{{ item.username }}）<span
                      v-show="index != usersList[1].length - 1"
                      >、</span
                    ></span
                  >
                  <el-link icon="el-icon-edit" class="icon" @click="toEdit(1)"
                    >编辑</el-link
                  >
                </div>
              </li>
              <li class="clearfix">
                <el-checkbox
                  v-model="checked[2]"
                  true-label="1"
                  false-label="0"
                  disabled
                  class="fl"
                ></el-checkbox>
                <span class="level fl">监察审核（三级）账号：</span>
                <div class="fl accountBox">
                  <span v-for="(item, index) of usersList[2]" :key="index"
                    >{{ item.nickname }}（{{ item.username }}）<span
                      v-show="index != usersList[2].length - 1"
                      >、</span
                    ></span
                  >
                  <el-link icon="el-icon-edit" class="icon" @click="toEdit(2)"
                    >编辑</el-link
                  >
                </div>
              </li>
            </ul>
          </div>
        </el-col>
      </el-form>
      <el-dialog
        :close-on-click-modal="false"
        title="审核账号"
        :visible.sync="formVisible"
        width="550px"
        :modal-append-to-body="false"
        :append-to-body="true"
      >
        <el-form :inline="true" :model="ruleForm" :rules="rules" ref="ruleForm">
          <el-form-item label="审核账号" prop="users">
            <el-select
              v-model="ruleForm.users"
              filterable
              multiple
              placeholder="请选择"
            >
              <el-option
                v-for="item in usersOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancel()" class="cancel">取 消</el-button>
          <el-button type="primary" @click="save('ruleForm')" class="save"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-row>
  </div>
</template>

<script>
// import { mapState, mapActions } from "vuex";
export default {
  name: 'insuranceBaseConfig',
  data() {
    var validateUsers = (rule, value, callback) => {
      if (value.length > 3) {
        callback(new Error('最多可选 3 个'))
      } else {
        callback()
      }
    }
    return {
      areaId: '',
      choice: '',
      checkedThird: true,
      formVisible: false,
      ruleForm: {
        users: '',
      },
      usersOptions: [],
      rules: {
        users: [{ validator: validateUsers, trigger: 'change' }],
      },
      num: 0,
      usersList: {
        0: [],
        1: [],
        2: [],
      },
      checked: [],
      users: {
        0: [],
        1: [],
        2: [],
      },
      config: [],
      areasOptions: [],
    }
  },
  computed: {
    // ...mapState(["areasOptions"]),
  },
  async created() {
    //   初始化区域开关
    await this.getAreaTreeByUser()
    await this.getCheckUsers()
    this.getInsbaseconfig()
  },
  methods: {
    // ...mapActions(["getAreas"]),
    changeArea() {
      // this.getCheckUsers();
      this.getInsbaseconfig()
      // this.getAllInsbaseconfig();
    },
    getAreaTreeByUser() {
      return this.axios({
        method: 'post',
        url: 'api-m/paramconfig/expand/areaTreeByUser',
      })
        .then(
          (res) => {
            if (!res.data.hasError) {
              this.areasOptions = res.data.result
            } else {
              this.$message({
                message: res.data.errorMsg,
                type: 'error',
              })
            }
          },
          (res) => {
            this.$message({
              message: res.data.errorMsg,
              type: 'error',
            })
          }
        )
        .catch((error) => {})
    },
    getInsbaseconfig() {
      this.axios({
        method: 'post',
        url: 'api-d/insbaseconfig/detail',
        data: {
          areaId: this.areaId,
        },
      })
        .then(
          (res) => {
            if (!res.data.hasError) {
              if (res.data.result) {
                this.choice = res.data.result.choice
                if (res.data.result.areaId) {
                  if (res.data.result.areaId == this.areaId || !this.areaId) {
                    this.areaId = res.data.result.areaId
                  }
                } else {
                  this.areaId = this.areasOptions[0].value
                }
                if (res.data.msg) {
                  this.$message({
                    message: res.data.msg,
                    type: 'warning',
                  })
                }

                this.getAllInsbaseconfig(res.data.result.insCheckConfigs)
              } else {
                this.choice = '0'
              }
            } else {
              this.$message({
                message: res.data.errorMsg,
                type: 'error',
              })
            }
          },
          (res) => {
            this.$message({
              message: res.data.errorMsg,
              type: 'error',
            })
          }
        )
        .catch((error) => {})
    },
    getAllInsbaseconfig(insCheckConfigs) {
      this.config = insCheckConfigs
      this.usersList = {
        0: [],
        1: [],
        2: [],
      }
      this.users = {
        0: [],
        1: [],
        2: [],
      }
      insCheckConfigs.forEach((item, index) => {
        if (item.insCheckDetailVOS) {
          item.insCheckDetailVOS.forEach((each, i) => {
            // each.status
            this.checked[index] = each.status

            this.usersOptions.forEach((ele, j) => {
              if (each.userId == ele.id) {
                this.usersList[index].push(each)
              }
            })
            this.users[index].push(each.userId)
            if (index == 2) {
              this.checked[index] = '1'
            }
          })
        } else {
          this.users[index] = []
          this.users = Object.assign({}, this.users, {})
          //审核当前级别是否关闭
          this.checked[index] = '0'
          if (index == 2) {
            this.checked[index] = '1'
          }
        }
      })
    },
    // genfig111() {
    //   this.axios({
    //     method: "post",
    //     url: "api-d/inscheckconfig/all",
    //     data: {
    //       areaId: this.areaId,
    //     },
    //   }).then(
    //     (res) => {
    //       if (!res.data.hasError) {
    //         this.config = res.data.result;
    //         this.usersList = {
    //                 0:[],
    //                 1:[],
    //                 2:[]
    //               };
    //         res.data.result.forEach((item, index) => {
    //           if (item.insCheckDetailVOS) {
    //             console.log(1)
    //             item.insCheckDetailVOS.forEach((each, i) => {
    //               // each.status
    //               this.checked[index] = each.status;

    //               this.usersOptions.forEach((ele, j) => {
    //                 if (each.userId == ele.id) {
    //                   this.usersList[index].push(each);
    //                 }
    //               });
    //               this.users[index].push(each.userId);
    //               if(index == 2){
    //                 this.checked[index] = "1";
    //               }
    //             });
    //           } else {

    //             this.users[index] = [];
    //             this.users = Object.assign({},this.users,{})
    //             //审核当前级别是否关闭
    //             this.checked[index] = "0";
    //             if(index == 2){
    //               this.checked[index] = "1";
    //             }
    //           }
    //         });
    //       } else {
    //         this.$message({
    //           message: res.data.errorMsg,
    //           type: "error",
    //         });
    //       }
    //     },
    //     (res) => {
    //       this.$message({
    //         message: res.data.errorMsg,
    //         type: "error",
    //       });
    //     }
    //   );
    //   // .catch(error => {});
    // },
    changeChoice() {
      this.getCheckUsers()
    },
    getCheckUsers() {
      return this.axios({
        method: 'post',
        url: 'api-d/inscheckconfig/checkUsers',
        data: {
          userType: 'MONITOR',
          isChecked: this.choice,
        },
      })
        .then(
          (res) => {
            if (!res.data.hasError && res.data.result) {
              this.usersOptions = res.data.result
              // this.getAllInsbaseconfig();
            } else {
              this.$message({
                message: res.data.errorMsg,
                type: 'error',
              })
            }
          },
          (res) => {
            this.$message({
              message: res.data.errorMsg,
              type: 'error',
            })
          }
        )
        .catch((error) => {})
    }, //
    cancel() {
      this.formVisible = false
    },
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.usersList[this.num] = []
          this.ruleForm.users.forEach((item, index) => {
            this.usersOptions.forEach((each, i) => {
              if (item == each.id) {
                this.usersList[this.num].push(each)
              }
            })
          })
          this.users[this.num] = this.ruleForm.users
          this.formVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    toEdit(num) {
      // if(num != this.num)
      this.ruleForm.users = this.users[num]
      this.num = num
      this.formVisible = true
    },
    // 保存
    toSave() {
      var insCheckDetails = []
      for (var i in this.users) {
        var each = this.users[i]
        if (each.length < 1) {
          insCheckDetails.push({
            checkConfigId: this.config[i].id,
            userId: '',
            status: this.checked[i],
          })
        } else {
          each.forEach((item, index) => {
            insCheckDetails.push({
              checkConfigId: this.config[i].id,
              userId: item,
              status: this.checked[i],
            })
          })
        }
      }
      for (var i = 0; i < insCheckDetails.length; i++) {
        if (insCheckDetails[i].status == '1' && !insCheckDetails[i].userId) {
          this.$message({
            message: '请选择审核人员',
            type: 'warning',
          })
          return
        }
      }
      this.axios({
        method: 'post',
        url: 'api-d/insbaseconfig/add',
        data: {
          areaId: this.areaId,
          choice: this.choice,
          insCheckDetails: JSON.stringify(insCheckDetails),
        },
      })
        .then(
          (res) => {
            if (!res.data.hasError) {
              this.$message({
                message: res.data.msg,
                type: 'success',
              })
            } else {
              this.$message({
                message: res.data.errorMsg,
                type: 'error',
              })
            }
          },
          (res) => {
            // this.$message({
            //   message: res.data.errorMsg,
            //   type: "error"
            // });
          }
        )
        .catch((error) => {})
    },
  },
}
</script>

<style scoped lang="less">
.box {
  padding: 16px 24px;
}

.el-form-item {
  margin-bottom: 0;
}

.border {
  margin-top: 16px;
  border: 1px solid #eef0f2;
  padding: 16px;
  //   开关设置
  .switch {
    margin: 24px 0 14px;
    span {
      margin: 0 16px;
      color: #333;
      font-size: 14px;
    }
  }
  //   审核配置
  .audit {
    margin: 24px 0 14px;
    li {
      margin-bottom: 24px;
      .el-checkbox {
        margin-top: 2px;
      }
      .level {
        color: #333;
        font-weight: 700;
        margin-left: 8px;
        margin-right: 10px;
        vertical-align: middle;
      }
      .accountBox {
        font-size: 14px;
        color: #333;
        line-height: 21px;
      }
      .icon {
        margin-left: 12px;
        // cursor: pointer;
      }
    }
    li:nth-last-type {
      margin-bottom: 14px;
    }
  }
}
</style>
